import request from './request'

const API_PREFIX = '/media'

/**
 * TypeScript 接口定义
 */

export interface MediaFile {
  fileId: number
  originalFileName: string
  fileType: 'image' | 'video' | 'audio' | 'document'
  extension: string
  fileSize: number
  filePath: string
  thumbnailUrl?: string
  previewUrl?: string
  originalUrl: string
  duration?: number
  dimensions?: string
  createTime: string
  updateTime: string
  uploaderId: number
  uploaderName: string
  tags: string[]
  description?: string
  isFavorite: boolean
  isPublic: boolean
  viewCount: number
  downloadCount: number
  metadata?: Record<string, any>
  exifData?: Record<string, any>
  location?: {
    latitude: number
    longitude: number
    address?: string
  }
}

export interface SmartAlbum {
  albumId: number
  name: string
  description?: string
  coverImage?: string
  rules: {
    tags?: string[]
    dateRange?: {
      startDate: string
      endDate: string
    }
    fileTypes?: string[]
    people?: string[]
    locations?: string[]
  }
  isPublic: boolean
  mediaCount: number
  createTime: string
  updateTime: string
}

export interface BatchTask {
  taskId: string
  type: string
  status: 'pending' | 'running' | 'completed' | 'failed'
  progress: number
  totalItems: number
  processedItems: number
  failedItems: number
  startTime: string
  endTime?: string
  result?: any
  error?: string
}

export interface MediaStatistics {
  totalFiles: number
  totalSize: number
  fileTypes: Record<string, number>
  uploadTrends: Array<{
    date: string
    count: number
    size: number
  }>
  storageUsage: {
    used: number
    total: number
    percentage: number
  }
  popularTags: Array<{
    tag: string
    count: number
  }>
}

export interface ShareLink {
  shareId: number
  shareToken: string
  shareUrl: string
  password?: string
  expireAt?: string
  downloadLimit?: number
  downloadCount: number
  allowPreview: boolean
  requireLogin: boolean
  createTime: string
  isActive: boolean
}

export interface AIClassificationResult {
  fileId: number
  objects: Array<{
    name: string
    confidence: number
    boundingBox?: {
      x: number
      y: number
      width: number
      height: number
    }
  }>
  scenes: Array<{
    name: string
    confidence: number
  }>
  faces: Array<{
    faceId: number
    personName?: string
    confidence: number
    boundingBox: {
      x: number
      y: number
      width: number
      height: number
    }
    landmarks?: Record<string, any>
  }>
  tags: string[]
  colors: Array<{
    color: string
    percentage: number
  }>
}

/**
 * 媒体文件相关接口
 */

// 单文件上传
export function uploadMediaFile(formData: FormData, onUploadProgress?: (progressEvent: any) => void) {
  return request({
    url: `${API_PREFIX}/upload`,
    method: 'post',
    data: formData,
    headers: {
      'Content-Type': 'multipart/form-data'
    },
    onUploadProgress,
    timeout: 300000 // 5分钟超时
  })
}

// 批量文件上传
export function batchUploadMediaFiles(formData: FormData, onUploadProgress?: (progressEvent: any) => void) {
  return request({
    url: `${API_PREFIX}/batch-upload`,
    method: 'post',
    data: formData,
    headers: {
      'Content-Type': 'multipart/form-data'
    },
    onUploadProgress
  })
}

// 获取媒体文件列表
export function getMediaFileList(params: {
  pageNum?: number
  pageSize?: number
  fileType?: string
}): Promise<{
  data: {
    list: MediaFile[]
    total: number
    pageNum: number
    pageSize: number
  }
}> {
  return request({
    url: `${API_PREFIX}/list`,
    method: 'get',
    params
  })
}

// 搜索媒体文件
export function searchMediaFiles(params: {
  keyword: string
  pageNum?: number
  pageSize?: number
}) {
  return request({
    url: `${API_PREFIX}/search`,
    method: 'get',
    params
  })
}

// 根据标签查询文件
export function getMediaFilesByTags(params: {
  tags: string
  pageNum?: number
  pageSize?: number
}) {
  return request({
    url: `${API_PREFIX}/by-tags`,
    method: 'get',
    params
  })
}

// 获取最近上传的文件
export function getRecentMediaFiles(limit = 10) {
  return request({
    url: `${API_PREFIX}/recent`,
    method: 'get',
    params: { limit }
  })
}

// 获取收藏的文件
export function getFavoriteMediaFiles(params: {
  pageNum?: number
  pageSize?: number
}) {
  return request({
    url: `${API_PREFIX}/favorites`,
    method: 'get',
    params
  })
}

// 获取文件详情
export function getMediaFileDetail(fileId: number): Promise<{
  data: MediaFile
}> {
  return request({
    url: `${API_PREFIX}/${fileId}`,
    method: 'get'
  })
}

// 切换收藏状态
export function toggleMediaFileFavorite(fileId: number) {
  return request({
    url: `${API_PREFIX}/${fileId}/toggle-favorite`,
    method: 'post'
  })
}

// 更新文件标签
export function updateMediaFileTags(fileId: number, tags: string) {
  return request({
    url: `${API_PREFIX}/${fileId}/tags`,
    method: 'put',
    params: { tags }
  })
}

// 移动到回收站
export function moveMediaFileToTrash(fileId: number) {
  return request({
    url: `${API_PREFIX}/${fileId}/trash`,
    method: 'post'
  })
}

// 从回收站恢复
export function restoreMediaFileFromTrash(fileId: number) {
  return request({
    url: `${API_PREFIX}/${fileId}/restore`,
    method: 'post'
  })
}

// 永久删除文件
export function deleteMediaFile(fileId: number) {
  return request({
    url: `${API_PREFIX}/${fileId}`,
    method: 'delete'
  })
}

// 批量删除文件
export function batchDeleteMediaFiles(fileIds: number[]) {
  return request({
    url: `${API_PREFIX}/batch`,
    method: 'delete',
    params: { fileIds: fileIds.join(',') }
  })
}

// 生成分享链接
export function generateMediaFileShareLink(fileId: number, expireHours = 24) {
  return request({
    url: `${API_PREFIX}/${fileId}/share`,
    method: 'post',
    params: { expireHours }
  })
}

// 获取存储统计
export function getStorageStats() {
  return request({
    url: `${API_PREFIX}/storage/stats`,
    method: 'get'
  })
}

// 根据时间范围查询文件
export function getMediaFilesByTimeRange(params: {
  startTime?: string
  endTime?: string
  pageNum?: number
  pageSize?: number
}) {
  return request({
    url: `${API_PREFIX}/by-time-range`,
    method: 'get',
    params
  })
}

// 文件下载
export function downloadMediaFile(fileId: number) {
  return request({
    url: `${API_PREFIX}/${fileId}/download`,
    method: 'get',
    responseType: 'blob'
  })
}

// 获取家庭公共文件
export function getFamilyMediaFiles(familyId: number, params: {
  pageNum?: number
  pageSize?: number
}) {
  return request({
    url: `${API_PREFIX}/family/${familyId}`,
    method: 'get',
    params
  })
}

/**
 * 智能相册相关接口
 */

// 创建智能相册
export function createSmartAlbum(params: {
  name: string
  description?: string
  coverImage?: string
  rules?: {
    tags?: string[]
    dateRange?: {
      startDate: string
      endDate: string
    }
    fileTypes?: string[]
    people?: string[]
    locations?: string[]
  }
  isPublic?: boolean
}) {
  return request({
    url: `${API_PREFIX}/albums/smart`,
    method: 'post',
    data: params
  })
}

// 获取智能相册列表
export function getSmartAlbumList(params: {
  pageNum?: number
  pageSize?: number
  type?: 'smart' | 'manual' | 'all'
}): Promise<{
  data: {
    list: SmartAlbum[]
    total: number
  }
}> {
  return request({
    url: `${API_PREFIX}/albums`,
    method: 'get',
    params
  })
}

// 获取智能相册详情
export function getSmartAlbumDetail(albumId: number) {
  return request({
    url: `${API_PREFIX}/albums/${albumId}`,
    method: 'get'
  })
}

// 更新智能相册
export function updateSmartAlbum(albumId: number, params: {
  name?: string
  description?: string
  coverImage?: string
  rules?: any
  isPublic?: boolean
}) {
  return request({
    url: `${API_PREFIX}/albums/${albumId}`,
    method: 'put',
    data: params
  })
}

// 删除智能相册
export function deleteSmartAlbum(albumId: number) {
  return request({
    url: `${API_PREFIX}/albums/${albumId}`,
    method: 'delete'
  })
}

// 手动添加媒体到相册
export function addMediaToAlbum(albumId: number, fileIds: number[]) {
  return request({
    url: `${API_PREFIX}/albums/${albumId}/media`,
    method: 'post',
    data: { fileIds }
  })
}

// 从相册移除媒体
export function removeMediaFromAlbum(albumId: number, fileIds: number[]) {
  return request({
    url: `${API_PREFIX}/albums/${albumId}/media`,
    method: 'delete',
    data: { fileIds }
  })
}

/**
 * AI 智能分类相关接口
 */

// 触发 AI 智能分类
export function triggerAIClassification(params: {
  fileIds?: number[]
  mode?: 'single' | 'batch' | 'all'
  features?: string[]
}) {
  return request({
    url: `${API_PREFIX}/ai/classify`,
    method: 'post',
    data: params
  })
}

// 获取 AI 分类结果
export function getAIClassificationResult(taskId: string): Promise<{
  data: AIClassificationResult
}> {
  return request({
    url: `${API_PREFIX}/ai/classify/${taskId}`,
    method: 'get'
  })
}

// 人脸识别和标记
export function detectFaces(fileId: number) {
  return request({
    url: `${API_PREFIX}/ai/faces/${fileId}`,
    method: 'post'
  })
}

// 获取人脸识别结果
export function getFaceDetectionResult(fileId: number) {
  return request({
    url: `${API_PREFIX}/ai/faces/${fileId}`,
    method: 'get'
  })
}

// 标记人物
export function tagPerson(faceId: number, personName: string) {
  return request({
    url: `${API_PREFIX}/ai/faces/${faceId}/tag`,
    method: 'post',
    data: { personName }
  })
}

// 获取识别的人物列表
export function getRecognizedPeople() {
  return request({
    url: `${API_PREFIX}/ai/people`,
    method: 'get'
  })
}

// 根据人物查找媒体
export function getMediaByPerson(personName: string, params: {
  pageNum?: number
  pageSize?: number
}) {
  return request({
    url: `${API_PREFIX}/by-person`,
    method: 'get',
    params: { ...params, personName }
  })
}

// 场景识别
export function detectScenes(fileId: number) {
  return request({
    url: `${API_PREFIX}/ai/scenes/${fileId}`,
    method: 'post'
  })
}

// 物体识别
export function detectObjects(fileId: number) {
  return request({
    url: `${API_PREFIX}/ai/objects/${fileId}`,
    method: 'post'
  })
}

// 智能搜索（基于AI分析结果）
export function intelligentSearch(params: {
  query: string
  searchType?: 'content' | 'people' | 'objects' | 'scenes' | 'all'
  pageNum?: number
  pageSize?: number
}) {
  return request({
    url: `${API_PREFIX}/ai/search`,
    method: 'get',
    params
  })
}

/**
 * 批量处理相关接口
 */

// 批量操作：移动到文件夹
export function batchMoveFiles(fileIds: number[], targetFolder: string) {
  return request({
    url: `${API_PREFIX}/batch/move`,
    method: 'post',
    data: { fileIds, targetFolder }
  })
}

// 批量操作：复制文件
export function batchCopyFiles(fileIds: number[], targetFolder: string) {
  return request({
    url: `${API_PREFIX}/batch/copy`,
    method: 'post',
    data: { fileIds, targetFolder }
  })
}

// 批量操作：添加标签
export function batchAddTags(fileIds: number[], tags: string[]) {
  return request({
    url: `${API_PREFIX}/batch/tags/add`,
    method: 'post',
    data: { fileIds, tags }
  })
}

// 批量操作：移除标签
export function batchRemoveTags(fileIds: number[], tags: string[]) {
  return request({
    url: `${API_PREFIX}/batch/tags/remove`,
    method: 'post',
    data: { fileIds, tags }
  })
}

// 批量操作：设置权限
export function batchSetPermissions(fileIds: number[], permissions: {
  isPublic?: boolean
  allowedUsers?: number[]
  allowedRoles?: string[]
}) {
  return request({
    url: `${API_PREFIX}/batch/permissions`,
    method: 'post',
    data: { fileIds, permissions }
  })
}

// 批量图片处理（压缩、转格式等）
export function batchImageProcess(params: {
  fileIds: number[]
  operations: {
    resize?: { width?: number; height?: number; quality?: number }
    format?: string
    compress?: { quality: number }
    watermark?: { text?: string; image?: string; position?: string }
  }
}) {
  return request({
    url: `${API_PREFIX}/batch/image-process`,
    method: 'post',
    data: params
  })
}

// 获取批量处理任务状态
export function getBatchTaskStatus(taskId: string): Promise<{
  data: BatchTask
}> {
  return request({
    url: `${API_PREFIX}/batch/task/${taskId}`,
    method: 'get'
  })
}

/**
 * 元数据和EXIF信息相关接口
 */

// 获取媒体文件元数据
export function getMediaMetadata(fileId: number) {
  return request({
    url: `${API_PREFIX}/${fileId}/metadata`,
    method: 'get'
  })
}

// 更新媒体文件元数据
export function updateMediaMetadata(fileId: number, metadata: {
  title?: string
  description?: string
  keywords?: string[]
  location?: {
    latitude?: number
    longitude?: number
    address?: string
  }
  customFields?: Record<string, any>
}) {
  return request({
    url: `${API_PREFIX}/${fileId}/metadata`,
    method: 'put',
    data: metadata
  })
}

// 提取EXIF信息
export function extractExifData(fileId: number) {
  return request({
    url: `${API_PREFIX}/${fileId}/exif`,
    method: 'post'
  })
}

// 获取地理位置信息的媒体
export function getGeoTaggedMedia(params: {
  bounds?: {
    northeast: { lat: number; lng: number }
    southwest: { lat: number; lng: number }
  }
  radius?: { center: { lat: number; lng: number }; radius: number }
  pageNum?: number
  pageSize?: number
}) {
  return request({
    url: `${API_PREFIX}/geo-tagged`,
    method: 'get',
    params
  })
}

/**
 * 文件版本和历史相关接口
 */

// 获取文件版本历史
export function getFileVersionHistory(fileId: number) {
  return request({
    url: `${API_PREFIX}/${fileId}/versions`,
    method: 'get'
  })
}

// 创建文件版本
export function createFileVersion(fileId: number, formData: FormData) {
  return request({
    url: `${API_PREFIX}/${fileId}/versions`,
    method: 'post',
    data: formData,
    headers: { 'Content-Type': 'multipart/form-data' }
  })
}

// 恢复到指定版本
export function restoreFileVersion(fileId: number, versionId: number) {
  return request({
    url: `${API_PREFIX}/${fileId}/versions/${versionId}/restore`,
    method: 'post'
  })
}

// 删除文件版本
export function deleteFileVersion(fileId: number, versionId: number) {
  return request({
    url: `${API_PREFIX}/${fileId}/versions/${versionId}`,
    method: 'delete'
  })
}

/**
 * 分享和权限相关接口
 */

// 设置文件权限
export function setMediaFilePermissions(fileId: number, permissions: {
  isPublic?: boolean
  allowedUsers?: number[]
  allowedRoles?: string[]
  permissions?: string[]
}) {
  return request({
    url: `${API_PREFIX}/${fileId}/permissions`,
    method: 'put',
    data: permissions
  })
}

// 获取文件权限信息
export function getMediaFilePermissions(fileId: number) {
  return request({
    url: `${API_PREFIX}/${fileId}/permissions`,
    method: 'get'
  })
}

// 创建高级分享链接（带密码、时效等）
export function createAdvancedShareLink(fileId: number, options: {
  password?: string
  expireAt?: string
  downloadLimit?: number
  allowPreview?: boolean
  requireLogin?: boolean
}): Promise<{
  data: ShareLink
}> {
  return request({
    url: `${API_PREFIX}/${fileId}/share/advanced`,
    method: 'post',
    data: options
  })
}

// 获取分享链接信息
export function getShareLinkInfo(shareToken: string) {
  return request({
    url: `${API_PREFIX}/share/${shareToken}`,
    method: 'get'
  })
}

// 通过分享链接访问文件
export function accessSharedFile(shareToken: string, password?: string) {
  return request({
    url: `${API_PREFIX}/share/${shareToken}/access`,
    method: 'post',
    data: { password }
  })
}

// 撤销分享链接
export function revokeShareLink(fileId: number, shareId: number) {
  return request({
    url: `${API_PREFIX}/${fileId}/share/${shareId}`,
    method: 'delete'
  })
}

/**
 * 统计和分析相关接口
 */

// 获取媒体文件统计信息
export function getMediaStatistics(): Promise<{
  data: MediaStatistics
}> {
  return request({
    url: `${API_PREFIX}/statistics`,
    method: 'get'
  })
}

// 获取文件类型分布
export function getFileTypeDistribution() {
  return request({
    url: `${API_PREFIX}/statistics/file-types`,
    method: 'get'
  })
}

// 获取上传趋势
export function getUploadTrends(params: {
  period?: 'week' | 'month' | 'year'
  startDate?: string
  endDate?: string
}) {
  return request({
    url: `${API_PREFIX}/statistics/trends`,
    method: 'get',
    params
  })
}

// 获取热门标签
export function getPopularTags(limit = 20) {
  return request({
    url: `${API_PREFIX}/statistics/tags`,
    method: 'get',
    params: { limit }
  })
}

// 获取存储使用详情
export function getStorageUsageDetails() {
  return request({
    url: `${API_PREFIX}/statistics/storage-details`,
    method: 'get'
  })
}

/**
 * 回收站相关接口
 */

// 获取回收站文件列表
export function getTrashFileList(params: {
  pageNum?: number
  pageSize?: number
}) {
  return request({
    url: `${API_PREFIX}/trash`,
    method: 'get',
    params
  })
}

// 清空回收站
export function emptyTrash() {
  return request({
    url: `${API_PREFIX}/trash/empty`,
    method: 'post'
  })
}

// 批量从回收站恢复
export function batchRestoreFromTrash(fileIds: number[]) {
  return request({
    url: `${API_PREFIX}/trash/batch-restore`,
    method: 'post',
    data: { fileIds }
  })
}

/**
 * 缩略图和预览相关接口
 */

// 生成缩略图
export function generateThumbnail(fileId: number, params: {
  width?: number
  height?: number
  quality?: number
}) {
  return request({
    url: `${API_PREFIX}/${fileId}/thumbnail`,
    method: 'post',
    data: params
  })
}

// 获取预览URL
export function getPreviewUrl(fileId: number, size?: 'small' | 'medium' | 'large') {
  return request({
    url: `${API_PREFIX}/${fileId}/preview`,
    method: 'get',
    params: { size }
  })
}

// 生成视频帧预览
export function generateVideoFrames(fileId: number, params: {
  count?: number
  interval?: number
  width?: number
  height?: number
}) {
  return request({
    url: `${API_PREFIX}/${fileId}/video-frames`,
    method: 'post',
    data: params
  })
}

/**
 * 导入导出相关接口
 */

// 从外部平台导入媒体
export function importFromExternalPlatform(params: {
  platform: string
  credentials: Record<string, any>
  options?: {
    includeMetadata?: boolean
    createAlbums?: boolean
    filterTypes?: string[]
  }
}) {
  return request({
    url: `${API_PREFIX}/import/external`,
    method: 'post',
    data: params
  })
}

// 导出媒体到外部平台
export function exportToExternalPlatform(params: {
  platform: string
  fileIds: number[]
  credentials: Record<string, any>
  options?: Record<string, any>
}) {
  return request({
    url: `${API_PREFIX}/export/external`,
    method: 'post',
    data: params
  })
}

// 导出为压缩包
export function exportAsArchive(params: {
  fileIds: number[]
  format?: 'zip' | 'tar'
  includeMetadata?: boolean
}) {
  return request({
    url: `${API_PREFIX}/export/archive`,
    method: 'post',
    data: params,
    responseType: 'blob'
  })
}

// 获取导入导出任务状态
export function getImportExportTaskStatus(taskId: string) {
  return request({
    url: `${API_PREFIX}/import-export/task/${taskId}`,
    method: 'get'
  })
}